package com.iweb.user.dao;

import com.iweb.user.model.User;
import com.iweb.util.JdbcUtil;
import java.util.List;
import java.util.Map;

public class UserDaoImpl implements UserDao {

    @Override
    public User queryByUsernameAndPassword(String username, String password) {
        String sql = "select userid,username,userfullname,password,phone from tb_user where username = ? and password = ?";
        List<Map<String, Object>> list = JdbcUtil.selectBySql(sql, username, password);

        // 如果查询到用户，创建并返回User对象
        if (list.size() > 0) {
            Map<String, Object> map = list.get(0);
            Integer userid = (Integer) map.get("userid");
            String userfullname = (String) map.get("userfullname");
            String phone = (String) map.get("phone");
            return new User(userid, username, userfullname, password, phone);
        }

        // 没有找到用户，返回null
        return null;
    }

    @Override
    public long findByUsername(String username) {
        String sql = "select count(*) from tb_user where username = ?";
        List<Map<String, Object>> list = JdbcUtil.selectBySql(sql, username);
        Map<String, Object> map = list.get(0);
        return (long) map.get("count(*)");
    }

    @Override
    public int saveOne(User user) {
        String sql = "insert into tb_user(username,userfullname,password,phone) values(?,?,?,?)";
        return JdbcUtil.editBySql(sql, user.getUsername(), user.getUserfullname(),
                user.getPassword(), user.getPhone());
    }

    @Override
    public User getUserById(int userId) {
        String sql = "select userid,username,userfullname,password,phone from tb_user where userid = ?";
        List<Map<String, Object>> list = JdbcUtil.selectBySql(sql, userId);

        // 如果查询到用户，创建并返回User对象
        if (list.size() > 0) {
            Map<String, Object> map = list.get(0);
            Integer userid = (Integer) map.get("userid");
            String username = (String) map.get("username");
            String userfullname = (String) map.get("userfullname");
            String password = (String) map.get("password");
            String phone = (String) map.get("phone");
            return new User(userid, username, userfullname, password, phone);
        }

        // 没有找到用户，返回null
        return null;
    }

    @Override
    public boolean deleteUser(int userId) {
        String sql = "delete from tb_user where userid = ?";
        int result = JdbcUtil.editBySql(sql, userId);
        return result > 0;
    }

    @Override
    public boolean updateUser(User user) {
        String sql = "update tb_user set userfullname = ?, phone = ?, password = ? where userid = ?";
        int result = JdbcUtil.editBySql(sql, user.getUserfullname(), user.getPhone(), user.getPassword(), user.getUserid());
        return result > 0;
    }
}
